package com.wiscamp.ninechapters.threeparties.qiniu;

import cube.ddd.aspect.HandleServiceException;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Qiniu Uploader Service
 */
@Service
public class QiniuService {

    @Value("${qiniu.access.key}")
    private String accesskey;

    @Value("${qiniu.secret.key}")
    //@Value("8Az-p_0ltOJWkTx71vKMDcA1PaTGmVtwL2PiBt00")
    private String secretKey;

    @Value("${qiniu.bucket.name}")
    private String bucketName;

    @Value("${qiniu.bucket.host.name}")
    private String bucketHostName;

    @Value("${qiniu.bucket.path}")
    private String bucketPath;

    /**
     * Uploads a file
     *
     * @param file
     * @return
     * @throws UploadQiniuException
     */

    @HandleServiceException
    public String uploadFile(@NotNull MultipartFile file) throws UploadQiniuException {
        var uploader = UploaderFactory.createUploader(this.accesskey, this.secretKey, this.bucketHostName,
                this.bucketName);
        return uploader.uploadFile(bucketPath, file);
    }

    /**
     * Uploads a file
     *
     * @param file
     * @return
     * @throws UploadQiniuException
     */

    @HandleServiceException
    public String uploadFile(@NotNull File file) throws UploadQiniuException {
        return uploadFile(file, bucketPath);
    }

    /**
     * Uploads a file
     *
     * @param file
     * @param path
     * @return
     * @throws UploadQiniuException
     */

    @HandleServiceException
    public String uploadFile(@NotNull File file, @NotBlank String path) throws UploadQiniuException {
        var uploader = UploaderFactory.createUploader(this.accesskey, this.secretKey, this.bucketHostName,
                this.bucketName);
        return uploader.uploadFile(path, file);
    }

    /**
     * Uploads binary data to server and writes a file
     *
     * @param data
     * @param fileName
     * @return
     * @throws UploadQiniuException
     */

    @HandleServiceException
    public String uploadFile(byte[] data, @NotBlank String fileName) throws UploadQiniuException {
        var uploader = UploaderFactory.createUploader(this.accesskey, this.secretKey, this.bucketHostName,
                this.bucketName);
        return uploader.uploadFile(data, fileName, bucketPath);
    }

    @HandleServiceException
    public String uploadFile(byte[] data, @NotBlank String fileName, @NotBlank String folderPath) throws UploadQiniuException {
        var uploader = UploaderFactory.createUploader(this.accesskey, this.secretKey, this.bucketHostName,
                this.bucketName);
        return uploader.uploadFile(data, fileName, bucketPath + folderPath);
    }
}
